﻿// *----------------------------------------------------------------
// Copyright (C) 2017 通通优品
// 版权所有。
// 
// 类名：QuartzScheduleJobManager.cs
// 功能描述：TongTongMall.Quartz
// 
// Create User：jym 2017/02/16
// 
// Edit User：UserName,EditTime
// Describe：Describe
// ----------------------------------------------------------------*/
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TongTongMall.Dependecy;

namespace TongTongMall.Quartz.Quartz
{
    public class QuartzScheduleJobManager : IQuartzScheduleJobManager, ISingletonDependency
    {
        private readonly IQuartzConfiguration _quartzConfiguration;

        public QuartzScheduleJobManager(
            IQuartzConfiguration quartzConfiguration)
        {
            _quartzConfiguration = quartzConfiguration;
        }

        /// <summary>
        /// 增加任务与任务调度到任务工厂
        /// </summary>
        /// <typeparam name="TJob"></typeparam>
        /// <param name="configureJob">任务</param>
        /// <param name="configureTrigger">任务调度</param>
        /// <returns></returns>
        public Task ScheduleAsync<TJob>(Action<JobBuilder> configureJob, Action<TriggerBuilder> configureTrigger)
            where TJob : IJob
        {
            var jobToBuild = JobBuilder.Create<TJob>();
            configureJob(jobToBuild);

            var job = jobToBuild.Build();

            var triggerToBuild = TriggerBuilder.Create();
            configureTrigger(triggerToBuild);
            var trigger = triggerToBuild.Build();

            _quartzConfiguration.Scheduler.ScheduleJob(job, trigger);

            return Task.FromResult(0);
        }

        /// <summary>
        /// 启动任务
        /// </summary>
        public void Start()
        {
            //启动任务调度框架
            if (!_quartzConfiguration.Scheduler.IsStarted)
            {
                _quartzConfiguration.Scheduler.Start();
            }
        }

        /// <summary>
        /// 等待任务完成并停止任务
        /// </summary>
        public void ShutDown()
        {
            if (_quartzConfiguration.Scheduler.IsStarted && !_quartzConfiguration.Scheduler.IsShutdown)
            {
                _quartzConfiguration.Scheduler.Shutdown();
            }
        }
    }
}
